package com.feng.security.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.GifCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import com.feng.common.dto.LoginDto;
import com.feng.common.utils.SecurityUtil;
import com.feng.common.utils.UploadUtil;
import com.feng.common.vo.ApiRest;
import com.feng.security.entity.User;
import com.feng.security.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author feng
 * @since 2023-03-21 09:22:39
 */
@RestController
@RequestMapping("/security/user")
@CrossOrigin
@Api(tags = "系统——权限模块")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("verify")
    @ApiOperation("获取验证码")
    public void getCodeImg(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 创建验证码
        GifCaptcha gif = CaptchaUtil.createGifCaptcha(200, 100);
        // 一位数运算验证码
        gif.setGenerator(new MathGenerator(1));
        SecurityUtil.gif = gif;
        gif.write(resp.getOutputStream());
    }

    @PostMapping("login")
    @ApiOperation("登录")
    public ApiRest login(@RequestBody LoginDto loginDto) {
        return userService.login(loginDto);
    }

    @GetMapping("power")
    @ApiOperation("前端权限验证")
    public ApiRest pathPower(@RequestHeader String token) {
        return userService.pathPower(token);
    }

    @PostMapping("headImg")
    @ApiOperation("用户头像上传")
    public ApiRest<String> uploadHeadImg(MultipartFile file) {
        return UploadUtil.uploadFile(file);
    }

    @PostMapping("editUser")
    @ApiOperation("修改用户信息")
    @Transactional
//    @PreAuthorize("hasAnyAuthority()")
    public ApiRest editUserInfo(@RequestBody User user) {
        return userService.updateById(user) ?
                ApiRest.success() : ApiRest.failure();
    }
}
